package org.example.mall4j.Handler;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.mall4j.common.CustomerAuthenionException;
import org.example.mall4j.common.Result;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component("loginFiledHandler")
public class LoginFailedHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
//        //1.设置响应编码
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream out = response.getOutputStream();
        String str = null;
        int code = 500;
        if(exception instanceof AccountExpiredException){
            str = "账户过期，登录失败!";
        }else if(exception instanceof BadCredentialsException){
            str = "用户名或密码错误，登录失败!";
        }else if(exception instanceof CredentialsExpiredException){
            str = "密码过期，登录失败!";
        }else if(exception instanceof DisabledException){
            str = "账户被禁用，登录失败!";
        }else if(exception instanceof LockedException){
            str = "账户被锁，登录失败!";
        }else if(exception instanceof InternalAuthenticationServiceException){
            str = "账户不存在，登录失败!";
        }else if(exception instanceof CustomerAuthenionException){


            //token验证失败
            code = 600;
            str = exception.getMessage();
        } else{
            str = "登录失败!";
        }
        // 设置返回格式
        String res = JSONObject.toJSONString(Result.fail(str));
        out.write(res.getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }
}

